<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Eloquent\Projects;
use App\Eloquent\TradeRecords;
use App\Eloquent\User;
use App\Admin\Eloquent\Message;
use App\Http\Controllers\Controller;
use App\Admin\Eloquent\ProjectsUser;
use App\Admin\Eloquent\ProjectProfit;
use App\Admin\Eloquent\GiftActivity;
use App\Admin\Eloquent\Code;
use App\Admin\Eloquent\OrganizationalUser;
use App\Admin\Eloquent\Information;
use App\Admin\Eloquent\Profit;
use App\Admin\Eloquent\ProfitRole;
use App\Admin\Eloquent\UserInfo;
use App\Admin\Eloquent\GiftReceive;
use Log;
use DB;
use Exception;
use CreateHostingCollectTrade;
use CreateSingleHostingPayTrade;
use CreateBatchHostingPayTrade;
use CancelPreAuthTrade;
use CreateHostingDeposit;
use CreateHostingWithdraw;

class ReturnController extends Controller
{
  public function index(Request $q){
    
    $data=$q->all();
    //标的录入
    $project=Projects::find($data['id']);
    dd($project->sina_project());
    //代收
    $sina_data1=[
      'out_trade_no'=>createSn(),
      'out_trade_code'=>'1001',
      'summary'=>'代收红包冻结金额',
      'payer_id'=>config('sinapay.payer_id'),
      'payer_identity_type'=>config('sinapay.payer_type'),
      'amount'=>$data['money'],
      'pay_method'=>'balance^'.$data['money'].'^'.config('sinapay.gift_payer_account'),
    ];
    // $result=json_decode(CreateHostingCollectTrade::send($sina_data1));
    //代付
    $sina_data=[
      'out_trade_no'=>createSn(),
      'out_trade_code'=>'2001',
      'payee_identity_id'=>$data['id'],
      'payee_identity_type'=>'UID',
      'account_type'=>'SAVING_POT',
      'amount'=>$data['money'],
      // 'split_list'=>'20160512172400^',
      'summary'=>'代付金额',
    ];
    // dump(CreateSingleHostingPayTrade::send($sina_data));
  }
	public function checkStatus($status){
		$success=array('PRE_AUTH_APPLY_SUCCESS','SUCCESS','TRADE_FINISHED','PAY_FINISHED');//成功响应的code
		$return=-1;
		if(in_array($status,$success)){
			$return=1;
		}
		return $return;
	}
	/**
	 * 代收还款回调
	 */
	public function payment(Request $q){
    $data=$q->all();
    $sn=$data['outer_trade_no'];

    $time=date('Y-m-d H:i:s');
    try {
      DB::beginTransaction();
      if(!CreateHostingCollectTrade::checkSignMsg($data)){throw new Exception("验签失败");}
      $records=TradeRecords::where('sn',$sn)->first();
      if($data['trade_status']=='PAY_FINISHED'){
        $status=1;
        //更新代收交易流水记录
        $user=User::find($records->pay_user);
        $balance=$user->queryBalance();
        $records->update(['pay_time'=>$time,'status'=>$status,'user_balance'=>$balance['available_balance']]);
        $profit=ProjectProfit::find($records->gift);
        $list=ProjectProfit::where(array('input_time'=>$profit->input_time,'project_id'=>$profit->project_id))->get();
        $split_list=array();
        $split_list_id=array();
        $trade_list=array();//代付流水记录
        foreach ($list as $item) {
          $profit_user=User::find($item->user_id);
          //判断用户是否设置支付密码
          if($profit_user->userInfo->is_set_pay_password){
            $sn=createSn();
            $remarks='代付还款金';
            $money=$item->money+$item->profit;
            $trade_list[]=array('sn'=>$sn,'type'=>3,'project_id'=>$item->project_id,'pay_user'=>$user->id,
              'receive_user'=>$item->user_id,'money'=>$money,'remarks'=>'代付还款金','created_at'=>$time,'gift'=>$item->id);
            $split_list[]=$sn.'~'.$profit_user->identity_id.'~UID~SAVING_POT~'.$money.'~~'.$remarks;
          }
        }
        //代付
        $sina_data=[
          'out_pay_no'=>createSn(),
          'out_trade_code'=>'2002',
          'trade_list'=>implode('$',$split_list),
          'notify_method'=>'single_notify',
          'notify_url'=>config('sinapay.notify_url').'/return/repayment',
        ];
        $result=CreateBatchHostingPayTrade::send($sina_data);
        if($result['response_code']!='APPLY_SUCCESS'){
          throw new Exception($result['response_message']);
        }
        //添加代付交易流水记录
        TradeRecords::insert($trade_list);
      }

      DB::commit();
    } catch (Exception $e) {
      DB::rollback();
      Log::info($e->getMessage());
    }
    ob_clean();
    echo 'success';
    exit;
	}
  /**
   * 代付还款回调
   */
  public function repayment(Request $q){
    $data=$q->all();
    $sn=$data['outer_trade_no'];
    $time=date('Y-m-d H:i:s');

    if(CreateHostingCollectTrade::checkSignMsg($data)){
      //是否代付成功
      $status=$this->checkStatus($data['trade_status']);
      $records=TradeRecords::where('sn',$sn)->first();
      $profit=ProjectProfit::find($records->gift);
      $project=Projects::find($profit->project_id);
      $user=User::find($records->pay_user);
      //更新还款记录
      $profit->update(['status'=>$status,'pay_time'=>$time]);
      //更新代收交易流水记录
      $balance=$user->queryBalance();
      $records->update(['pay_time'=>$time,'status'=>$status,'user_balance'=>$balance['available_balance']]);
      //还款完成,更新项目
      if(ProjectProfit::where(['project_id'=>$project->id])->whereIn('status',[0,-1])->count()==0){
        $project->update(['status'=>'finish','trade_finish_date'=>$time]);
      }
      //发送站内信给经纪人
      $broker=UserInfo::where('invite_code',$user->userInfo->broker_code)->value('user_id');
      $content=$user->userInfo->name.'客户于'.date('Y年m月d日').'还款项目'.$project->projects_name.',还款金额:'.$records->money;
      Message::sendMessage('sys_msg','还款提醒',$content,$broker);
    }
    ob_clean();
    echo 'success';
    exit;
  }
  /**
   * 分润回调
   * @return [type] [description]
   */
  public function profit(Request $q){
    $data=$q->all();
    $sn=$data['outer_trade_no'];
    Log::info('分润回调');
    Log::info($data);
    $time=date('Y-m-d H:i:s');
    try {
      DB::beginTransaction();
      if(!CreateHostingCollectTrade::checkSignMsg($data)){throw new Exception("验签失败");}
      $records=TradeRecords::where('sn',$sn)->first();
      if($data['trade_status']=='PAY_FINISHED' && !empty($records)){
        $status=1;
        //更新交易流水记录
        $records->update(['pay_time'=>$time,'status'=>$status]);
        //更新分润记录
        $profit=ProjectProfit::where('sn',$sn)->first();
        if($profit){
          $profit->update(['pay_time'=>$time,'status'=>$status]);
        }
      }

      DB::commit();
    } catch (Exception $e) {
      DB::rollback();
      Log::info($e->getMessage());
    }
    ob_clean();
    echo 'success';
    exit;
  }
	/**
   * 充值回调
   * @return [type] [description]
   */
  public function recharge(Request $q){
    $data=$q->all();
    Log::info('充值回调');
    Log::info($data);
    $records=TradeRecords::where('sn',$data['outer_trade_no'])->first();
    if(CreateHostingDeposit::checkSignMsg($data) && $records){
      $user=User::find($records->pay_user);
     	$balance=$user->queryBalance();
      $status=$this->checkStatus($data['deposit_status']);
     	$update=['pay_time'=>date('Y-m-d H:i:s'),'status'=>$status,'user_balance'=>$balance['available_balance']];
      //判断充值是否成功
    	if($status==1){
        $pay_method1=explode('^',$data['pay_method']);
        $pay_method=explode(',',$pay_method1[2]);

        $update['card_number']=$pay_method[0];
	      //判断是否首次充值
	      if(TradeRecords::where('pay_user',$records->pay_user)->where('type',4)->where('status',1)->count()==1){
	        GiftActivity::sendGift('gift_grant_rule_6',$records->pay_user);
	      }
      }else{
        $update['remarks']=$records->remarks;
    	}
      $records->update($update);
    }
    ob_clean();
    echo 'success';
    exit;
  }
  /**
   * 提现回调
   * @return [type] [description]
   */
  public function withdraw(Request $q){
    $data=$q->all();
    Log::info('提现回调');
    Log::info($data);
    if(CreateHostingWithdraw::checkSignMsg($data)){
    	$records=TradeRecords::where('sn',$data['outer_trade_no'])->first();
      $user=User::find($records->pay_user);
      $balance=$user->queryBalance();
      $status=$this->checkStatus($data['withdraw_status']);
      if($status==-1){
        $data['card_id']=null;
      }
      //更新记录
      $records->where('sn',$data['outer_trade_no'])->update([
      	'pay_time'=>date('Y-m-d H:i:s'),
      	'user_balance'=>$balance['available_balance'],
      	'status'=>$status,
      	'card_number'=>$data['card_id'],
      ]);
    }
    ob_clean();
    echo 'success';
    exit;
  }
  /**
   * 投资回调
   * @param  Request $q [description]
   * @return [type]     [description]
   */
  public function investProject(Request $q){
    $data=$q->all();
    Log::info('投资回调');
    Log::info($data);
  	$sn=$data['outer_trade_no'];
    $time=date('Y-m-d H:i:s');
    $records=TradeRecords::where('sn',$sn)->first();
    if(CreateHostingCollectTrade::checkSignMsg($data) && $records){
      $status=$this->checkStatus($data['trade_status']);
      $user=User::find($records->pay_user);
      $balance=$user->queryBalance();
      //判断回调的结果
      if($data['trade_status']=='PRE_AUTH_APPLY_SUCCESS' && $records->status==0){
        try {
          DB::beginTransaction();
          //更新交易流水记录
          $records->update(['pay_time'=>$time,'status'=>$status,'user_balance'=>$balance['available_balance']]);
          if($status<0){throw new Exception('交易失败');}

          $project=Projects::find($records->project_id);
          $profit=$project->getProfit1($records->money);//预期收益
          //更新项目的已投金额,判断项目是否已投满
          $financed_money=$project->financed_money+$records->money;
          if($financed_money==$project->finance_money){
            $project->update(['status'=>'full','financed_money'=>$financed_money,'trade_finish_date'=>$time]);
          }elseif($financed_money<$project->finance_money){
            $project->update(['financed_money'=>$financed_money]);
          }else{
            //撤销代收
            $result=TradeRecords::cancelTrade([$records->sn],'投资撤销',config('sinapay.notify_url').'/return/cancelInvest');
            if($result['response_code']!='APPLY_SUCCESS'){abort(600,$result['response_message']);}
            throw new Exception('项目已满标');
          }
      		//添加投资记录
        	ProjectsUser::insert([
        		'sn'=>$sn,
        		'projects_id'=>$records->project_id,
            'identity_id'=>$user->identity_id,
        		'user_id'=>$records->pay_user,
        		'user_name'=>$user->userInfo->name,
        		'invest_money'=>$records->money,
        		'invest_time'=>$time,
            'org_code'=>$user->userInfo->org_code,
            'dept_code'=>$user->userInfo->dept_code,
            'broker_code'=>$user->userInfo->broker_code,
            'second_broker_code'=>$user->userInfo->second_broker_code,
            'gift'=>$records->gift,
            'expected_return'=>$profit['all']['profit'],
        	]);
          
          //更新用户投资时间
          $user->update(['last_invest_at'=>$time]);

          //判断是否含有红包投资
          $gift_records=TradeRecords::where('pid',$records->id)->where('type',7)->get();
          if(!empty($gift_records)){
            foreach ($gift_records as $item) {
              $sina_data1=[
                'out_trade_no'=>$item->sn,
                'out_trade_code'=>'1001',
                'summary'=>$item->remarks,
                'payer_id'=>config('sinapay.payer_id'),
                'payer_identity_type'=>config('sinapay.payer_type'),
                'amount'=>$item->money,
                'pay_method'=>'balance^'.$item->money.'^'.config('sinapay.gift_payer_account'),
                'notify_url'=>config('sinapay.notify_url').'/return/investGift',
              ];
              //代收商户金额
              $result=json_decode(CreateHostingCollectTrade::send($sina_data1));
              if($result->response_code!='APPLY_SUCCESS'){
                Log::warning('代收红包金额：'.$result->response_message);
              } 
            }
          }
          //发送站内信给经纪人
          $broker=UserInfo::where('invite_code',$user->userInfo->broker_code)->value('user_id');
          $content=$user->userInfo->name.'客户于'.date('Y年m月d日').'投资'.$project->projects_name.'项目'.$records->money.'元';
          Message::sendMessage('sys_msg','投资提醒',$content,$broker);
          //发送短信给投资人
          // if(!empty($user->phone_number)){
          //   $content=Information::where()->first();
          //   phone_code($user->phone_number);
          // }

          DB::commit();
        } catch (Exception $e) {
          DB::rollback();
          Log::warning('投资失败!'.$e->getMessage());
        }
      }

      //代收完成
      if($data['trade_status']=='TRADE_FINISHED'){
        $records->update(['status'=>3]);
        $project_user=ProjectsUser::where('projects_id',$records->project_id)->count();
        $records_list=TradeRecords::where(['project_id'=>$records->project_id,'status'=>3])->count();
        if($records_list==$project_user){
          TradeRecords::where(['project_id'=>$records->project_id,'type'=>8])->update(['pay_time'=>$time,'status'=>1]);
        }
      }
      //发放现金红包
      if($data['trade_status']=='PAY_FINISHED'){}
    }else{
      Log::info('验证签名失败');
    }
    ob_clean();
    echo 'success';
    exit;
  }
  /**
   * 使用红包投资回调
   * @return [type] [description]
   */
  public function investGift(Request $q){
    $data=$q->all();
    $sn=$data['outer_trade_no'];
    $time=date('Y-m-d H:i:s');
    if(CreateHostingCollectTrade::checkSignMsg($data)){
      try {
        DB::beginTransaction();
        //判断回调的结果
        $status=$this->checkStatus($data['trade_status']);
        if($data['trade_status']=='PAY_FINISHED'){
          $records=TradeRecords::where('sn',$sn)->first();
          $user=User::find($records->pay_user);
          $balance=$user->queryBalance();
          //更新交易流水记录
          $records->update(['pay_time'=>$time,'status'=>$status,'user_balance'=>$balance['available_balance']]);
          if($status<0){throw new Exception('交易失败');}
          //更新项目
          $project=Projects::find($records->project_id);
          $profit=$project->getProfit($records->money);
          //更新项目的已投金额,判断项目是否已投满
          $financed_money=$project->financed_money+$records->money;
          if($financed_money==$project->finance_money){
            $project->update(['status'=>'full','financed_money'=>$financed_money,'trade_finish_date'=>$time]);
          }elseif($financed_money<$project->finance_money){
            $project->update(['financed_money'=>$financed_money]);
          }else{
            //撤销代收
            // $result=TradeRecords::cancelTrade([$records->sn],'投资撤销',config('sinapay.notify_url').'/return/cancelInvest');
            // if($result['response_code']!='APPLY_SUCCESS'){abort(600,$result['response_message']);}
            throw new Exception('项目已满标');
          }
          //对应投资流水号
          $psn=TradeRecords::where('id',$records->pid)->value('sn');
          $project_user=ProjectsUser::where('sn',$psn)->first();
          $gift=$project_user->gift;
          if(!$gift){
            $gift=$records->gift;
          }else{
            $gift.=','.$records->gift;
          }
          $project_user->increment('invest_money',$records->money,['gift'=>$gift]);
          //更新红包状态
          GiftReceive::where('id',$records->gift)->update(['status'=>1,'use_time'=>$time]);
          //发送站内信给经纪人
          $broker=UserInfo::where('invite_code',$user->userInfo->broker_code)->value('user_id');
          $content=$user->userInfo->name.'客户于'.date('Y年m月d日').'使用红包投资'.$project->projects_name.'项目'.$records->money.'元';
          Message::sendMessage('sys_msg','红包投资提醒',$content,$broker);
        }

        DB::commit();
      } catch (Exception $e) {
        DB::rollback();
        Log::info('投资失败!'.$e->getMessage());
      }
    }else{
      Log::info('验证签名失败');
    }
    ob_clean();
    echo 'success';
    exit;
  }
  /**
   * 撤销投资的回调
   * @param  Request $q [description]
   */
  public function cancelInvest(Request $q){
    $data=$q->all();
    $sn=$data['outer_trade_no'];
    $time=date('Y-m-d H:i:s');
    if(CreateHostingCollectTrade::checkSignMsg($data)){
      $records=TradeRecords::where('sn',$sn)->first();
      $user=User::find($records->pay_user);
      $balance=$user->queryBalance();
      //判断回调的结果
      $status=$this->checkStatus($data['trade_status']);
      if($status==1){
        //更新交易流水记录
        $records->update(['pay_time'=>$time,'status'=>-1,'user_balance'=>$balance['available_balance']]);
     }else{
        Log::warning('撤销失败：'.$sn);
     }
    }
    ob_clean();
    echo 'success';
    exit;
  }
  /**
   * 代收撤销回调(撤销项目)
   * @return [type] [description]
   */
  public function cancelTrade(Request $q){
    $data=$q->all();
    Log::info('回调撤销项目');
    Log::info($data);
    $time=date('Y-m-d H:i:s');
    if(CreateHostingCollectTrade::checkSignMsg($data)){

    }
    ob_clean();
    echo 'success';
    exit;
  }
  /**
   * 撤销回调(红包投资金额)
   * @param  Request $q [description]
   * @return [type]     [description]
   */
  public function cancelGift(Request $q){
    $data=$q->all();
    Log::info('撤销红包投资');
    Log::info($data);
    $time=date('Y-m-d H:i:s');
    if(CreateHostingCollectTrade::checkSignMsg($data)){

    }
    ob_clean();
    echo 'success';
    exit;
  }

  /**
   * 回调发送现金红包
   * @return [type] [description]
   */
  public function sendGift(Request $q){
    $data=$q->all();
    $sn=$data['outer_trade_no'];
    if(CreateHostingCollectTrade::checkSignMsg($data)){
      $records=TradeRecords::where('sn',$sn)->first();
      $user=User::find($records->receive_user);
      $balance=$user->queryBalance();
      $status=$this->checkStatus($data['trade_status']);
      //更新交易流水记录
      $records->update([
        'pay_time'=>date('Y-m-d H:i:s'),
        'status'=>$status,
        'user_balance'=>$balance['available_balance']
      ]);

      //更新红包状态
      GiftReceive::where('id',$records->gift)->update(['status'=>1]);
    }
    ob_clean();
    echo 'success';
    exit;
  }

  /**
   * 代付到银行卡(封包-融资人收钱)
   * @return [type] [description]
   */
  public function payCard(Request $q){
    $data=$q->all();
    Log::info('代付到银行卡回调');
    Log::info($data);
    $sn=$data['outer_trade_no'];
    $time=date('Y-m-d H:i:s');
    if(CreateHostingCollectTrade::checkSignMsg($data)){
      $records=TradeRecords::where('sn',$sn)->first();
      $status=$this->checkStatus($data['withdraw_status']);
      if($status>0){
        $records->update(['status'=>$status,'pay_time'=>$time]);
      }

    }
    ob_clean();
    echo 'success';
    exit;
  }
}